package net.lab1024.sa.admin.module.business.exam.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.admin.module.business.exam.dao.*;
import net.lab1024.sa.admin.module.business.exam.domain.entity.*;
import net.lab1024.sa.admin.module.business.exam.domain.form.add.ExamromaAddForm;
import net.lab1024.sa.admin.module.business.exam.domain.form.query.ExamromaQueryForm;
import net.lab1024.sa.admin.module.business.exam.domain.form.update.ExamromaUpdateForm;
import net.lab1024.sa.admin.module.business.exam.domain.vo.ExamromaVO;
import net.lab1024.sa.admin.module.system.employee.dao.EmployeeDao;
import net.lab1024.sa.admin.module.system.employee.domain.entity.EmployeeEntity;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * 日历明细 Service
 *
 * @Author AKITA
 * @Date 2025-06-06 11:34:55
 * @Copyright AKITA
 */

@Service
public class ExamromaService {

    @Resource
    private ExamromaDao examromaDao;
    @Resource
    private ExamrombDao examrombDao;
    @Resource
    private PaperaDao paperaDao;
    @Resource
    private QuestionsaDao questionsaDao;
    @Resource
    private EmployeeDao employeeDao;
    @Resource
    private PaperService paperService;
    @Resource
    private ExamromDao examromDao;

    public PageResult<ExamromaVO> queryPage(ExamromaQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<ExamromaVO> list = examromaDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    public ResponseDTO<String> add(ExamromaAddForm addForm) {
        ExamromaEntity examromaEntity = SmartBeanUtil.copy(addForm, ExamromaEntity.class);
        examromaDao.insert(examromaEntity);
        return ResponseDTO.ok();
    }

    public ResponseDTO<String> update(ExamromaUpdateForm updateForm) {
        ExamromaEntity examromaEntity = SmartBeanUtil.copy(updateForm, ExamromaEntity.class);
        int update = examromaDao.update(examromaEntity, new LambdaQueryWrapper<ExamromaEntity>().eq(ExamromaEntity::getDocEntry, examromaEntity.getDocEntry()).eq(ExamromaEntity::getLineNum, examromaEntity.getLineNum()).eq(ExamromaEntity::getVersion, examromaEntity.getVersion()));
        if (update == 0){
            throw new RuntimeException("数据已被更新，刷新后重试！");
        }
        return ResponseDTO.ok();
    }

    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        examromaDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    public ResponseDTO<String> delete(Long docEntry) {
        if (null == docEntry) {
            return ResponseDTO.ok();
        }

        examromaDao.deleteById(docEntry);
        return ResponseDTO.ok();
    }

    public ResponseDTO<ExamromaEntity> myInfo(Long docEntry) {
        Long requestUserId = SmartRequestUtil.getRequestUserId();
        ExamromaEntity examromaEntity = examromaDao.myInfo(requestUserId,docEntry);

        long epochSecond = examromaEntity.getBeginDate().toEpochSecond(ZoneOffset.of("+08:00"));
        long l1 = epochSecond + 120 * 60 ;
        long epochSecond1 = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+08:00"));
        if (epochSecond1 > l1){
            examromaEntity.setHour(0);
            examromaEntity.setMinute(0);
            examromaEntity.setSecond(0);
        } else {
            long l = 120 * 60 - (epochSecond1 - epochSecond);
            LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(l, 0, ZoneOffset.of("+00:00"));
            examromaEntity.setHour(localDateTime.getHour());
            examromaEntity.setMinute(localDateTime.getMinute());
            examromaEntity.setSecond(localDateTime.getSecond());
        }
        return ResponseDTO.ok(examromaEntity);
    }


    @Transactional
    public ResponseDTO<ExamromaEntity> openExam(Long docEntry) {
        Long requestUserId = SmartRequestUtil.getRequestUserId();
        ExamromaEntity examroma = examromaDao.selectOne(new LambdaQueryWrapper<ExamromaEntity>().eq(ExamromaEntity::getDocEntry, docEntry).eq(ExamromaEntity::getUserId, requestUserId));
        if (examroma.getLineStatus().equals("O")) {
            ExamromaEntity examromaEntity = new ExamromaEntity();
            examromaEntity.setBeginDate(LocalDateTime.now());
            examromaEntity.setLineStatus("L");
            examromaDao.update(examromaEntity,new LambdaQueryWrapper<ExamromaEntity>().eq(ExamromaEntity::getDocEntry,docEntry).eq(ExamromaEntity::getUserId,requestUserId));
        }
        return ResponseDTO.ok();
    }


    @Transactional
    public ResponseDTO<String> submitExam(ExamromaEntity examromaEntity) {
        BigDecimal score = BigDecimal.ZERO;
        int totalNum = 0;
        int errorNum = 0;
        for (ExamrombEntity examromb : examromaEntity.getLista()) {

            /**
             * 1、单选题
             * 2、多选
             * 3、判断
             * 4、填空
             * */
            if (examromb.getQuesTypeId() == 1) {


                for (QuestionsaEntity questionsa : examromb.getLista()) {

                    examromb.setCorrent(false);
                    examromb.setScore(BigDecimal.ZERO);

                    if (questionsa.getInspect()) {
                        if (questionsa.getInspecta()) {
                            examromb.setCorrent(true);
                            examromb.setScore(examromb.getBaseScore());
                            break;
                        }
                    }
                }

            } else if (examromb.getQuesTypeId() == 2) {
                for (QuestionsaEntity questionsa : examromb.getLista()) {
                    examromb.setCorrent(true);
                    examromb.setScore(examromb.getBaseScore());
                    if (questionsa.getInspect()) {
                        if (!questionsa.getInspecta()) {
                            examromb.setCorrent(false);
                            examromb.setScore(BigDecimal.ZERO);
                            break;
                        }
                    }
                }
            } else if (examromb.getQuesTypeId() == 3) {
                for (QuestionsaEntity questionsa : examromb.getLista()) {
                    examromb.setCorrent(false);
                    examromb.setScore(BigDecimal.ZERO);
                    if (questionsa.getInspect()) {
                        if (questionsa.getInspecta()) {
                            examromb.setCorrent(true);
                            examromb.setScore(examromb.getBaseScore());
                            break;
                        }
                    }
                }
            } else if (examromb.getQuesTypeId() == 4) {
                for (QuestionsaEntity questionsa : examromb.getLista()) {
                    examromb.setCorrent(false);
                    examromb.setScore(BigDecimal.ZERO);
                    if (questionsa.getAnswer().equals(questionsa.getAnswera())) {
                        examromb.setCorrent(true);
                        examromb.setScore(examromb.getBaseScore());
                        break;
                    }
                }
            }
            examrombDao.update(examromb, new LambdaQueryWrapper<ExamrombEntity>().eq(ExamrombEntity::getDocEntry, examromb.getDocEntry()).eq(ExamrombEntity::getLineNum, examromb.getLineNum()));
            examromaEntity.setScore(examromaEntity.getScore().add(examromb.getScore()));
            
            examromaEntity.setTotalNum(++totalNum);
            if (!examromb.getCorrent()) {
                examromaEntity.setErrorNum(++errorNum);
            }

        }
        examromaEntity.setEndDate(LocalDateTime.now());
        Duration between = Duration.between(examromaEntity.getBeginDate(), LocalDateTime.now());
        examromaEntity.setExamDur(BigDecimal.valueOf(between.getSeconds() / 60));
        examromaEntity.setLineStatus("C");

        int update = examromaDao.update(examromaEntity, new LambdaQueryWrapper<ExamromaEntity>().eq(ExamromaEntity::getDocEntry, examromaEntity.getDocEntry()).eq(ExamromaEntity::getLineNum, examromaEntity.getLineNum()).eq(ExamromaEntity::getVersion, examromaEntity.getVersion()));
        if (update == 0){
            throw new RuntimeException("数据已被更新，刷新后重试！");
        }
        return ResponseDTO.ok();
    }

    public ResponseDTO<List<ExamromaEntity>> querylist(Long docEntry) {
        List<ExamromaEntity> examromaEntities =  examromaDao.selectCountList(docEntry);
        return ResponseDTO.ok(examromaEntities);
    }


    @Transactional
    public ResponseDTO<String> batchAdd(List<Long> addForms, Long docEntry) {
        List<EmployeeEntity> employeeEntities = employeeDao.selectList(new LambdaQueryWrapper<EmployeeEntity>().in(EmployeeEntity::getEmployeeId, addForms));
        ExamromEntity examromEntity = examromDao.selectById(docEntry);
        ResponseDTO<PaperEntity> info = paperService.info(examromEntity.getPaperId());


        Integer i = examromaDao.selectLineNum(docEntry);
        if (i == null){
            i = 0;
        }
        Integer j = examrombDao.selectLineNum(docEntry);
        if (j == null){
            j = 0;
        }





        for (EmployeeEntity employeeEntity : employeeEntities) {
            ExamromaEntity examromaEntity = new ExamromaEntity();
            examromaEntity.setDocEntry(docEntry);
            examromaEntity.setLineNum(++i);
            examromaEntity.setLineStatus("O");
            examromaEntity.setUserId(employeeEntity.getEmployeeId());
            examromaEntity.setUserName(employeeEntity.getLoginName());
            examromaEntity.setVersion(1);
            examromaDao.insert(examromaEntity);
            for (PaperaEntity paperaEntity : info.getData().getLista()) {
                ExamrombEntity examrombEntity = new ExamrombEntity();
                examrombEntity.setDocEntry(docEntry);
                examrombEntity.setLineNum(++j);
                examrombEntity.setLineStatus("O");
                examrombEntity.setUserId(employeeEntity.getEmployeeId());
                examrombEntity.setUserName(employeeEntity.getLoginName());
                examrombEntity.setQuestion(paperaEntity.getQuestion());
                examrombEntity.setBaseScore(paperaEntity.getScore());
                examrombEntity.setQuesTypeId(paperaEntity.getQuesTypeId());
                examrombEntity.setQuesTypeName(paperaEntity.getQuesTypeName());
                examrombEntity.setBaseEntry(paperaEntity.getBaseEntry());
                examrombDao.insert(examrombEntity);
            }
        }

        return ResponseDTO.ok();
    }
}
